import React, { useEffect, useRef, useState } from "react";
import { listJob, delJob, exportJob, runJob, changeJobStatus, addJob, updateJob } from '@/api/monitor/job'
import SearchForm from "../../../components/searchForm";
import { Table, Divider, Button, message, Modal, Switch, Popconfirm } from "antd";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { download } from "../../../utils";
import { ModalForm } from "@ant-design/pro-components";
import { PlusOutlined, ExclamationCircleFilled, SnippetsOutlined, CaretRightOutlined, EyeOutlined } from '@ant-design/icons';
import JobForm from "./modules/jobForm";
import { getDicts } from "@/api/system/dict/data";
import ViewFormModal from "./modules/viewForm";
import { useDictionary } from "@/hooks";
import DisplayLabel from "@/components/displayLabel";
import { Link } from "react-router-dom";
const queryItems = [
  {
    name: 'jobName',
    label: '任务名称',
    type: 'INPUT',
  },
  {
    name: 'jobGroup',
    label: '任务组名',
    type: 'SELECT',
    dictType: 'sys_job_group'
  },
  ,
  {
    name: 'status',
    label: '任务状态',
    type: 'SELECT',
    dictType: 'sys_job_status'
  }
];
//i18n
const JobIndex = () => {
  useDictionary(['sys_job_status', 'sys_job_group']);
  const viewFormModalRef = useRef()
  const [searchParams, setSearchParams] = useState({});
  const [expandedRowKeys, setExpandedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [page, setPage] = React.useState({ pageNo: 1, pageSize: 10 });
  const confirm = Modal.confirm;
  const columns = [
    {
      title: '编号',
      dataIndex: 'jobId',
      width: '70px',
      align: 'center'
    },
    {
      title: '任务名称',
      dataIndex: 'jobName',
      ellipsis: true,
      align: 'center'
    },
    {
      title: '任务组名',
      dataIndex: 'jobGroup',
      align: 'center',
      render: (text) => (<DisplayLabel value={text} type="sys_job_group" />)
    },
    {
      title: '调用目标字符串',
      dataIndex: 'invokeTarget',
      ellipsis: true,
      align: 'center'
    },
    {
      title: 'cron执行表达式',
      dataIndex: 'cronExpression',
      ellipsis: true,
      align: 'center'
    },
    {
      title: '状态',
      dataIndex: 'status',
      // scopedSlots: { customRender: 'status' },
      align: 'center',
      render: (_, record) => (
        <>
          <Popconfirm onConfirm={() => confirmHandleStatus(record)} title={
            <>
              确认<b>{record.status === '1' ? '开启' : '关闭'}</b>{record.jobName}的任务吗?
            </>
          } >
            <Switch checkedChildren="开" unCheckedChildren="关" checked={record.status == 0}></Switch>
          </Popconfirm>
        </>
      )
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: '250px',
      render: (_, record) => (
        <>

          <Popconfirm title={`确认执行一次${record.jobName}的任务吗?`} onConfirm={() => confirmHandleRun(record)}>
            <a><CaretRightOutlined /> 执行一次</a>
          </Popconfirm>
          <Divider type="vertical" />
          <ModalForm
            trigger={<a>修改</a>}
            title={`修改【${record.jobName}】任务`}
            modalProps={{ destroyOnClose: true }}
            onFinish={handleSave}
            initialValues={{
              ...record
            }}
            grid={true}
          >
            <JobForm />
          </ModalForm>
          <Divider type="vertical" />
          <a onClick={() => { viewFormModalRef.current.showModal(record) }}><EyeOutlined /> 详细</a>
        </>
      ),
    },
  ];
  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['page-job-listJob', page, searchParams],
    queryFn: () => {
      return listJob({
        pageNum: page.pageNo,
        pageSize: page.pageSize,
        ...searchParams,
      }).then((res) => {
        return res || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
  })
  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }

  const handleRefreshCache = () => {
    refreshCache().then(() => {
      message.success('刷新成功')
    })
  }

  const handleSave = (values) => {
    if (values.jobId) {
      return updateJob(values).then(() => {
        refetch()
        message.success('修改成功')
        return true
      })
    } else {
      return addJob(values).then(() => {
        refetch()
        message.success('新增成功')
        return true
      })
    }
  }


  /* 任务状态修改 */
  const confirmHandleStatus = (row) => {
    const text = row.status === '1' ? '启用' : '停用'
    changeJobStatus(row.jobId, row.status === '0' ? '1' : '0')
      .then(() => {
        message.success(text + '成功')
        refetch()
      }).catch(function () {
        message.error(text + '发生异常')
      })
  }

  /* 立即执行一次 */
  const confirmHandleRun = (row) => {
    runJob(row.jobId, row.jobGroup)
      .then(() => {
        message.success('执行成功')
      }).catch(() => {
        message.error('发生异常')
      })
  }

  const deleteConfirm = (row) => {
    const dictIds = row.jobId || selectedRowKeys
    confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      content: `当前选中定时任务编号为"${dictIds}"的数据`,
      autoFocusButton: null,
      onOk() {
        return delJob(dictIds)
          .then(() => {
            onSelectChange([], [])
            refetch()
            message.success('删除成功')
          })
      },
      onCancel() { },
    });
  };

  const exportConfirm = () => {
    confirm({
      title: '是否确认导出?',
      content: '此操作将导出当前条件下所有数据而非选中数据',
      autoFocusButton: null,
      onOk() {
        return exportJob({
          pageNum: page.pageNo,
          pageSize: page.pageSize,
          ...searchParams,
        })
          .then(response => {
            download(response.msg)
            message.success('导出成功')
          })
      },
      onCancel() { },
    });
  }

  return (
    <div size="small" className="searchTableWrapper">
      <div className="searchTableHeader">定时任务</div>
      <SearchForm
        onSearch={(values) => setSearchParams({ ...values })}
        items={queryItems}
        buttons={<>
          <ModalForm
            trigger={<Button className="ml-2" icon={<PlusOutlined />} type="primary">新增</Button>}
            title="添加任务"
            modalProps={{ destroyOnClose: true }}
            onFinish={handleSave}
            grid={true}
            initialValues={{
              misfirePolicy: '1',
              concurrent: '1',
              status: '0'
            }}
          >
            <JobForm />
          </ModalForm>
          {selectedRowKeys.length > 0 && <Button className="ml-2" danger onClick={deleteConfirm}>批量删除</Button>}
          <Button className="ml-2" onClick={exportConfirm}>导出</Button>
          <Link to="/integration/log/joblog">
            <Button onClick={handleRefreshCache} icon={<SnippetsOutlined />}>日志</Button>
          </Link>
        </>}
      />
      <Table
        rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
        columns={columns}
        rowKey={(record) => record.jobId}
        loading={isFetching}
        dataSource={tableData?.rows}
        pagination={{
          current: page.pageNo,
          pageSize: page.pageSize,
          total: tableData?.total,
          onChange: (pageNo, pageSize) => {
            setPage({ pageNo, pageSize })
          }
        }}
      />
      <ViewFormModal ref={viewFormModalRef} />
    </div>
  );
};


export default JobIndex;
